package app.species;

import sim.engine.*;
import sim.util.*;

public class Bullet extends Entity{

	/**
	 * 
	 */
	private static final long serialVersionUID = -7919636685800479784L;

	private static int DEFAULT_INIT_ENERGY = 200;

	private static double DEFAULT_DIAMETER = 75.0;
	private static double DEFAULT_SENSE_DIST = 75.0;
	private static double DEFAULT_SPEED = 10.0;
	private static int DEFAULT_LIFE_SPAN = 0;

	public Bullet(MutableDouble2D initPos, MutableDouble2D initHead){

		super(initPos, initHead);

		this.setDiameter(Bullet.DEFAULT_DIAMETER);
		this.setSenseDistance(Bullet.DEFAULT_SENSE_DIST);
		this.setSpeed(Bullet.DEFAULT_SPEED);
		this.setLifeSpan(Bullet.DEFAULT_LIFE_SPAN);

		this.resetColor();

		this.setEnergy(Bullet.DEFAULT_INIT_ENERGY);

	}

	public Bullet(){ super(); }

	public static void setDefaults(double diameter, double speed, double senseDist, int lifeSpan){

		Bullet.DEFAULT_DIAMETER = diameter;
		Bullet.DEFAULT_SPEED = speed;
		Bullet.DEFAULT_SENSE_DIST = senseDist;
		Bullet.DEFAULT_LIFE_SPAN = lifeSpan;

	}

	public static void setInitialEnergy(int n){

		Bullet.DEFAULT_INIT_ENERGY = n;

	}

	public void step(SimState state){

		SpeciesSim sim = (SpeciesSim)state;

		this.interactFood(sim);

		if(this.getEnergy() <= 0){

			sim.removeEntityFromSim(this, sim.bullets);
			return;

		}else{
			this.addEnergy(-1);
		}

		/* when bullets hit walls, they die!
		 **/
		if(this.hittingWall(sim.fieldWidth, sim.fieldHeight)){

			sim.removeEntityFromSim(this, sim.bullets);
			return;

		}

		/* update the position in the Continuous2D container
		 * also, update the position within the agent
		 **/
		this.updatePosition();
		sim.bullets.setObjectLocation(this, new Double2D(this.position));

	}

	private void interactFood(SpeciesSim sim){

		Bag nearbyCreatures = sim.creatures.getObjectsWithinDistance(new Double2D(this.position), this.getSenseDistance());
		Creature creature;

		for(int i = 0; i < nearbyCreatures.numObjs; i++){

			creature = (Creature)nearbyCreatures.objs[i];

			// check to see if the bullet is touching the creature.  if it is, then kill the creature and continue to next one
			if(this.isTouching(creature)){

				sim.removeEntityFromSim(creature, sim.creatures);

			}

		}

	}

}
